﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Runtime.Serialization.Formatters.Binary;

namespace nr.Tombola.Windows.Player
{
    public partial class CardsManagerForm : Form
    {
        public List<nr.Tombola.Cards.Card> Cards
        {
            get
            {
                List<nr.Tombola.Cards.Card> result = new List<Cards.Card>();
                foreach (object obj in lbCards.Items)
                    result.Add(obj as nr.Tombola.Cards.Card);
                return result;
            }
            set
            {
                lbCards.Items.Clear();
                foreach (nr.Tombola.Cards.Card card in value)
                    lbCards.Items.Add(card);
            }
        }

        public CardsManagerForm()
        {
            InitializeComponent();
        }

        private void lbCards_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (lbCards.SelectedItem != null)
                cvCard.Card = lbCards.SelectedItems[0] as nr.Tombola.Cards.Card;
            bool enabled = lbCards.SelectedItem != null;
            btnDelete.Enabled = enabled;
            btnEdit.Enabled = enabled;
        }

        private void btnCreate_Click(object sender, EventArgs e)
        {
            CardsCreateForm frm = new CardsCreateForm();
            if (frm.ShowDialog(this) == System.Windows.Forms.DialogResult.OK)
            {
                int count = frm.CardsCount;
                string name = frm.CardsName;
                if (frm.CreateSeries)
                {
                    int index = 0;
                    while (count > 0)
                    {
                        lbCards.Items.AddRange(nr.Tombola.Cards.Card.Series(string.Format("{0}_{1}", name, ++index), frm.ReorderNumbers));
                        count -= 6;
                    }
                }
                else
                {
                    if (count == 1)
                        lbCards.Items.Add(nr.Tombola.Cards.Card.Random(name));
                    else
                        for (int index = 0; index < frm.CardsCount; ++index)
                            lbCards.Items.Add(nr.Tombola.Cards.Card.Random(string.Format("{0}[{1}]", frm.CardsName, index + 1), frm.ReorderNumbers));
                }
            }
        }

        private void btnDelete_Click(object sender, EventArgs e)
        {
            string message = string.Format("Vuoi davvero eliminare la cartella <{0}>?", lbCards.SelectedItem);
            if (MessageBox.Show(this, message, "[nr.Tombola] Controller di Gioco", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) == System.Windows.Forms.DialogResult.Yes)
            {
                cvCard.Card = null;
                int current = lbCards.SelectedIndex;
                lbCards.SelectedIndex = -1;
                lbCards.Items.RemoveAt(current);
                lbCards.SelectedIndex = current - 1;
            }
        }

        private void btnPrint_Click(object sender, EventArgs e)
        {
            if (dlgPrint.ShowDialog(this) == System.Windows.Forms.DialogResult.OK)
            {
                PrintCards(dlgPrint.PrinterSettings);
            }
        }

        private void PrintCards(System.Drawing.Printing.PrinterSettings settings)
        {
            document.PrinterSettings = settings;
            document.Print();
        }

        List<nr.Tombola.Cards.Card> printingCards;
        IEnumerator<nr.Tombola.Cards.Card> cursor;

        private void document_BeginPrint(object sender, System.Drawing.Printing.PrintEventArgs e)
        {
            printingCards = new List<Cards.Card>();

            if (document.PrinterSettings.PrintRange == System.Drawing.Printing.PrintRange.Selection)
                foreach (object o in lbCards.SelectedItems)
                    printingCards.Add(o as nr.Tombola.Cards.Card);
            else
                foreach (object o in lbCards.Items)
                    printingCards.Add(o as nr.Tombola.Cards.Card);
            cursor = printingCards.GetEnumerator();
        }

        private void document_EndPrint(object sender, System.Drawing.Printing.PrintEventArgs e)
        {

        }

        private void document_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs e)
        {
            e.HasMorePages = DrawPage(e.Graphics);
        }

        private void document_QueryPageSettings(object sender, System.Drawing.Printing.QueryPageSettingsEventArgs e)
        {
            document.DefaultPageSettings = e.PageSettings;
        }

        private bool DrawPage(Graphics graphics)
        {
            int left = document.DefaultPageSettings.Margins.Left;
            int top = document.DefaultPageSettings.Margins.Top;
            int pageHeight = (document.DefaultPageSettings.Bounds.Height - document.DefaultPageSettings.Margins.Top - document.DefaultPageSettings.Margins.Bottom - 20);
            int height = pageHeight / 3;
            int width = document.DefaultPageSettings.Bounds.Width - document.DefaultPageSettings.Margins.Left - document.DefaultPageSettings.Margins.Right;
            bool haveMoreCards = true;
            bool pageFilled = false;
            RectangleF rect = RectangleF.Empty;
            Font f = new Font(FontFamily.GenericSerif, 12);
            SizeF fontSize = graphics.MeasureString("Pp", f);
            StringFormat sf = new StringFormat();
            sf.Alignment = StringAlignment.Far;
            int headerHeight = (int)fontSize.Height + 4;
            float cellHeight = (height - headerHeight) / 3;
            float cellWidth = width / 9;
            float em = 100;
            do
            {
                f = new Font(FontFamily.GenericSerif, --em);
                fontSize = graphics.MeasureString("88", f);
            } while ((fontSize.Width > cellWidth) || (fontSize.Height > cellHeight));
            do
            {
                haveMoreCards = cursor.MoveNext();
                pageFilled = (top + height) > pageHeight;
                if (haveMoreCards)
                {
                    graphics.DrawRectangle(new Pen(Brushes.Black, 2), left, top, width, height);
                    graphics.DrawString(cursor.Current.Name, new Font(FontFamily.GenericSerif, 12), Brushes.Black, left + 2, top + 2);
                    top += headerHeight;
                    for (int counter = 1; counter < 9; ++counter)
                        graphics.DrawLine(Pens.Black, left + (counter * cellWidth), top, left + counter * cellWidth, top + height - headerHeight);
                    for (int counter = 0; counter < 3; ++counter)
                        graphics.DrawLine(Pens.Black, left, top + (counter * cellHeight), left + width, top + (counter * cellHeight));
                    for (int row = 0; row < 3; ++row)
                    {
                        for (int dec = 0; dec < 9; ++dec)
                            if (cursor.Current[row][dec] > 0)
                            {
                                rect = new RectangleF(
                                    left + dec * cellWidth, top + row * cellHeight,
                                    cellWidth, cellHeight);
                                graphics.DrawString(cursor.Current[row][dec].ToString(), f, Brushes.Black, rect, sf);
                            }
                    }
                    top += height + 10;
                }
            } while (haveMoreCards && !pageFilled);

            return haveMoreCards;
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            if (dlgSave.ShowDialog(this) == System.Windows.Forms.DialogResult.OK)
                using (System.IO.FileStream fs = new System.IO.FileStream(dlgSave.FileName, System.IO.FileMode.Create))
                {
                    BinaryFormatter f = new BinaryFormatter();
                    f.Serialize(fs, Cards);
                }
        }

        private void btnLoad_Click(object sender, EventArgs e)
        {
            if (dlgOpen.ShowDialog(this) == System.Windows.Forms.DialogResult.OK)
                using (System.IO.FileStream fs = new System.IO.FileStream(dlgOpen.FileName, System.IO.FileMode.Open))
                {
                    BinaryFormatter f = new BinaryFormatter();
                    Cards = (List<nr.Tombola.Cards.Card>)f.Deserialize(fs);
                }
        }

        private void btnEdit_Click(object sender, EventArgs e)
        {
            ManualCardCreateForm frm = new ManualCardCreateForm();
            frm.Text = "Modifica Cartella";
            frm.Card = cvCard.Card;
            if (frm.ShowDialog(this) == System.Windows.Forms.DialogResult.OK)
                cvCard.Card = frm.Card;
        }

        private void btnAddCard_Click(object sender, EventArgs e)
        {
            ManualCardCreateForm frm = new ManualCardCreateForm();
            frm.Text = "Inserimento Cartella";
            if (frm.ShowDialog(this) == System.Windows.Forms.DialogResult.OK)
                lbCards.Items.Add(frm.Card);
        }
    }
}
